//引入mongoose第三方模块
const mongoose = require('mongoose');
const admin = require('../route/admin');
//导入bcrypt的哈希加密
const bcrypt = require('bcryptjs');
//添加Joi模块
const Joi = require('joi');

//创建用户集合规则
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10
    },
    email: {
        type: String,
        //用于登录，保证唯一
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true,
    },
    role: {
        type: String,
        required: true,
    },
    state: {
        type: Number,
        //0 为启用状态 1为禁用状态
        default: 0
    }
});

//创建集合
const User = mongoose.model('User', userSchema);

async function createUser() {
    const salt = await bcrypt.genSalt(10);
    const pass = await bcrypt.hash('123123', salt);
    //创建初始登录用户
    const user = await User.create({
        username: 'bobo',
        email: '234@234.com',
        password: pass,
        role: 'admin',
        state: 0,
    })
};
// createUser();
//验证用户信息
const validateUser = (user) => {
    //创建验证规则
    const schema = {
        username: Joi.string().min(2).max(12).required().error(new Error('用户名不符合规则')),
        email: Joi.string().email().required().error(new Error('邮箱格式不符合要求')),
        password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}/).required().error(new Error('密码要求数字字母组合不低于3位')),
        role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值非法')),
        state: Joi.number().valid(0, 1).required().error(new Error('状态值非法')),
    };
    return Joi.validate(user, schema);
}

//将用户集合作为模块成员进行导出
module.exports = {
    User: User, //对象的键和值相同,可以只写一个。
    validateUser
};